package com.consumer.rabitmq;

import com.rabbitmq.client.Channel;
import com.redlight.rabbitmq.RabbitConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Created by chao on 2019/3/29.
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_A)
public class MsgReceiver {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(value = RabbitConfig.QUEUE_A,durable = "true"), //队列持久化
//            exchange = @Exchange(
//                    value = RabbitConfig.EXCHANGE_A,
//                    ignoreDeclarationExceptions = "true",
//                    type = ExchangeTypes.TOPIC
//            ),
////            key = {"item.insert","item.update"}
//            key = {RabbitConfig.ROUTINGKEY_A,RabbitConfig.ROUTINGKEY_A}
//    ))
//    public void process(String content, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag  ) {
////    public void process(String content) {
//        try {
//            logger.info("接收处理队列A当中的消息： " + content);
//            channel.basicAck(tag,false);            // 确认消息
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConfig.QUEUE_A,durable = "true"), //队列持久化
            exchange = @Exchange(
                    value = RabbitConfig.EXCHANGE_A,
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
//            key = {"item.insert","item.update"}
            key = {RabbitConfig.ROUTINGKEY_A,RabbitConfig.ROUTINGKEY_A}
    ))
    public void process2(String message, Channel channel,@Headers Map<String,Object> map ) {
//    public void process(String content) {
        System.out.println(message);
        if (map.get("error")!= null){
            System.out.println("错误的消息");
            try {
                channel.basicReject((Long)map.get(AmqpHeaders.DELIVERY_TAG),false);//直接被丢弃
//                channel.basicNack((Long)map.get(AmqpHeaders.DELIVERY_TAG),false,true);      //否认消息
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            channel.basicAck((Long)map.get(AmqpHeaders.DELIVERY_TAG),false);            //确认消息
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
